import { useEffect } from "react";
import _ from "lodash";
import { useImmer } from "use-immer";
import { get, set, del } from "idb-keyval";

export function useTabbyData(path, key, initialValue) {
  const [data, setData] = useImmer(initialValue);

  //初始化effect
  useEffect(() => {
    get(`[${path}]${key}`).then((val) => {
      if (val) {
        setData((draft) => {
          for (let i in val) {
            draft[i] = val[i];
          }
        });
      }
    });
  }, []);

  //data 值变化 effect
  useEffect(() => {
    if (_.isEqual(data, initialValue)) {
      del(`[${path}]${key}`);
      return;
    }

    get(`[${path}]${key}`).then((val) => {
      if (_.isEqual(val, data)) {
        return;
      } else {
        set(`[${path}]${key}`, data);
      }
    });
  }, [JSON.stringify(data)]);

  const reset = () => {
    setData(initialValue);
  };

  return [data, setData, reset];
}
